from pymongo import MongoClient

# 连接到MongoDB
client = MongoClient('localhost', 27017)  # 本地MongoDB服务器
db = client['WLQ_db']  # 数据库名称
collection = db[('WLQ_col')]  # 集合名称

# 读取TXT文件中的天气数据
weather_data = []

with open("weather_data.txt", "r", encoding="utf-8") as file:
    lines = file.readlines()

    day_info = {}
    for line in lines:
        line = line.strip()
        if line.startswith("Date:"):
            if day_info:  # 如果之前的数据已存在，存储它
                weather_data.append(day_info)
            day_info = {}  # 清空当前日数据
            day_info['date'] = line[6:]
        elif line.startswith("Weather:"):
            day_info['weather'] = line[9:]
        elif line.startswith("Wind:"):
            day_info['wind'] = line[6:]
        elif line.startswith("High Temperature:"):
            day_info['high_temp'] = line[18:]
        elif line.startswith("Low Temperature:"):
            day_info['low_temp'] = line[17:]
        elif line.startswith("Night Weather:"):
            day_info['night_weather'] = line[15:]

    # 确保最后一天的数据也被存储
    if day_info:
        weather_data.append(day_info)

# 将读取的数据写入MongoDB数据库
if weather_data:
    collection.insert_many(weather_data)
    print("数据已成功保存到MongoDB数据库。")
else:
    print("未能成功读取天气数据。")
